package com.yuecai.config;


import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuecai.modules.security.JwtUserDto;
import com.yuecai.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(urlPatterns = "/api/*")
public class RealNameFilter extends OncePerRequestFilter {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        JwtUserDto currentUser = (JwtUserDto) SecurityUtils.getCurrentUser();
        boolean realName = currentUser.getUser().isRealName();
        if (!realName){
            httpServletResponse.setStatus(HttpStatus.HTTP_BAD_REQUEST);
            ApiError error = ApiError.error(HttpStatus.HTTP_BAD_REQUEST, "请您先去实名认证！");
            String s = objectMapper.writeValueAsString(error);
            httpServletResponse.getWriter().println(s);
            log.info("-------------未实名---------");
            return;
        }else {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }
    }
}
